package com.wangsd.common.component;

import com.wangsd.web.sys.service.SysCompanyService;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;

@Component
@Slf4j
public class WxApiV3Service {

    @Autowired
    private SysCompanyService companyService;

    @Cacheable(value = "twoHour", key = "#root.targetClass.name + '-' + #subMchId", unless = "#result eq null")
    public CloseableHttpClient getHttpClient(String mchId, String mchSerialNo, String apiV3Key, String privateKey) {
        CloseableHttpClient httpClient = null;
        try {
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                    new ByteArrayInputStream(privateKey.getBytes("utf-8")));

            //使用自动更新的签名验证器，不需要传入证书
            AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                    new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
                    apiV3Key.getBytes("utf-8"));

            httpClient = WechatPayHttpClientBuilder.create()
                    .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                    .withValidator(new WechatPay2Validator(verifier))
                    .build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return httpClient;
    }
}
